#!/usr/bin/env python
# coding: utf-8
# from typing import Dict, Union
from datetime import datetime, timedelta
import freeswitch
from rediscluster import client
import time
import random
import demjson
import json


# <extension name="useGatewayCall">
#     <condition field="destination_number" expression="^3(\d+)$">
#         <action application="lua" data="testGateway.lua ${1}"/>
#     </condition>
# </extension>
# <extension name="busy">
#     <condition field="destination_number" expression="^user_busy$">
#         <action application="playback" data="/usr/local/freeswitch/sounds/user/lineBusy.wav"/>
#     </condition>
# </extension>

def handler(session, args):  # args is string
    # gatewayList = [{"gatewayName":"mx8", "lines":"1", "user":"19900000000", "url":"172.16.8.88", "contact":None},
    #                {"gatewayName":"ds", "lines":"3", "user":"19900000001", "url":"172.16.8.88", "contact":None}]
    # gatewayList=[{"gatewayName":"dx16_1903", "lines":"16", "user":"19900000003", "url":"172.16.200.60", "contact":None},
    #              {"gatewayName":"swx32_200_81", "lines":"32", "user":"19900000004", "url":"172.16.200.60", "contact":None}]
    gatewayList = [
        {"gatewayName": "swx32_200_81", "lines": "32", "user": "19900000004", "url": "172.16.200.60", "contact": None}]

    uuid = session.getVariable("uuid")
    # 获取数组长度
    count = len(gatewayList)
    if count == 0:
        freeswitch.console_log("err", "call %s exception,not found gateway! %s \n" % uuid)
        session.hangup("ORIGINATOR_CANCEL")

    session.setAutoHangup(False)  # #设置不要自动挂机, 否则当此脚本执行完, 会自动挂机
    selectGateway = None  # # 最终将会选用的网关
    # freeswitch的API
    api = freeswitch.API()

    # 随机选择一个gateway, 假如选到的gateway为空闲的, 就停止循环, 否则继续(要注意判断session的状态, 否则可能有死循环)
    while count > 0:
        # #选择list中的gateway
        gateway = random.choice(gatewayList)
        # 获取gatewayName
        gatewayName = gateway["gatewayName"]
        # 获取此网关注册到freeswitch的用户名
        gatewayUser = gateway["user"]
        # 查询当前gateway是否在线
        gatewayStatus = api.executeString("sofia status profile internal user " + gatewayUser + "@" + gateway["url"])

        beginIndex = gatewayStatus.find("User")
        if beginIndex is not None:  # 检测在线
            # 查询gateway已用线路
            result = api.execute("limit_usage", "hash gatewayList " + gatewayName)
            freeswitch.consoleLog("INFO", "当前网关为" + gatewayName + "使用已用线路:" + result + ",总可用为" + gateway[
                "lines"])  # 打印gateway线路日志

            # 检测已用线路等于最大线路, 就再继续随机选一个, 假如不是, 就选用这个gateway
            if result != gateway["lines"]:
                # 获取注册contact头
                contactBeginIndex = gatewayStatus.find("sip:" + gatewayUser + "@")
                contactEndIndex = gatewayStatus.find(">")
                gatewayContractStr = gatewayStatus[contactBeginIndex:contactEndIndex]
                gateway["contact"] = gatewayContractStr
                selectGateway = gateway  # #赋值给最终选择的gateway
                break
            else:
                freeswitch.consoleLog("INFO", "当前网关为" + gatewayName + "线路已满,重新选择")  # 打印gateway线路日志
        else:
            freeswitch.consoleLog("INFO", "网关" + gatewayName + "尚未注册")  # 打印gateway线路日志
            # session.hangup("ORIGINATOR_CANCEL")

        # 从list中踢出, 下次就不会选到了
        gatewayList.remove(gateway)
        # list总长度减1
        count = count - 1

    # #假如selectGateway(最终选用网关)不为空, 就用它呼出, 假如为空, 就表示全部gateway都忙线
    if selectGateway is not None:
        session.setVariable("gateway", selectGateway["gatewayName"])  # #设置app
        # limit参数
        session.setVariable("useBackend", "hash")  # #设置app
        # limit的backend参数
        session.setVariable("useRealm", "gatewayList")  # #设置app
        # limit的realm参数
        session.setVariable("lines", selectGateway["lines"])  # #设置app
        # limit的max参数
        session.setVariable("id", selectGateway["gatewayName"])  # #设置app
        # limit的resource参数
        session.setVariable("callContact", selectGateway["contact"])  # #设置外呼字符串的参数
        freeswitch.consoleLog("INFO", "最终选择外呼的网关为" + selectGateway["gatewayName"])  # #打印gateway线路日志

        # <action application="limit" data="${useBackend} ${useRealm} ${id} ${lines} user_busy XML default"/>
        # <action application="limit" data="db outgoing gw1 10" />
        session.execute("limit", "hash gatewayList %s %s user_busy XML default" %
                        (selectGateway["gatewayName"], selectGateway["lines"]))
        # call_str = "sofia/gateway/"+selectGateway["gatewayName"]+"/"+session.getVariable("calleeNumber")
        # <action application="bridge" data="{origination_caller_id_number=$1,origination_caller_id_name=$1}sofia/internal/$1@${callContact}"/>
        call_str = "{origination_caller_id_number=%s,origination_caller_id_name=%s}sofia/internal/%s@${callContact}" % \
                   (args, args, args, selectGateway["contact"])
        session.execute("bridge", call_str)
        session.hangup()
    else:
        custom_msg = "sessionId: " + session.get_uuid()
        e = freeswitch.Event("custom", "dial::lineBusy")
        e.addHeader("sessionId", session.get_uuid())
        e.addBody(custom_msg)
        e.fire()
        freeswitch.consoleLog("INFO", "当前没有任何的空闲线路了")  # #打印gateway线路日志
        session.streamFile("/usr/local/freeswitch/sounds/user/lineBusy.wav", "3")  # #假如没有线路, 播放忙音语音
        session.hangup("ORIGINATOR_CANCEL")
